package com.security.domain.authority;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 大忽悠
 * @create 2022/10/8 10:12
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class CommonUserDetails implements UserDetails {
    /**
     * 用户拥有的角色集合
     */
    private List<CommonRole> commonRoles;
    /**
     * 用户名
     */
    private String username;
    /**
     * 密码
     */
    private String password;
    /**
     * 是否启用
     */
    private Boolean enabled;
    /**
     * 账户是否没有过期
     */
    private boolean accountNonExpired;
    /**
     * 账户是否没有被锁定
     */
    private boolean accountNonLocked;
    /**
     * 密码是否没有过期
     */
    private boolean credentialsNonExpired;


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<CommonAuthority> authorities=new ArrayList<>();
        for (CommonRole commonRole : commonRoles) {
            authorities.addAll(commonRole.getAllowedOperations());
        }
        return authorities.stream().distinct().collect(Collectors.toList());
    }

    /**
     * @return 返回当前用户具备的角色列表
     */
    public Set<String> getUserRoles(){
        return commonRoles.stream().map(CommonRole::getAuthority).collect(Collectors.toSet());
    }


    @Override
    public String getUsername() {
        return username;
    }

    /**
     * @return 账户是否可用
     */
    @Override
    public boolean isEnabled() {
        return enabled;
    }


    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public boolean isAccountNonExpired() {
        return accountNonExpired;
    }

    @Override
    public boolean isAccountNonLocked() {
        return accountNonLocked;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return credentialsNonExpired;
    }
}
